{% import 'macro/svg.html' as SVG %}
{% import 'macro/oops.html' as OOPS %}
<div class="container-xl">
  <!-- Page title -->
  <div class="page-header d-print-none">
    <div class="row align-items-center">
      <div class="col">
        <h2 class="page-title">
          我的媒体库
        </h2>
      </div>
      <div class="col-auto ms-auto d-print-none">
        <div class="btn-list">
          <a href="javascript:show_mediasync_modal()" class="btn btn-primary d-none d-sm-inline-block">
            {{ SVG.refresh() }}
            媒体库同步
          </a>
          <a href="javascript:show_mediasync_modal()" class="btn btn-primary d-sm-none btn-icon">
            {{ SVG.refresh() }}
          </a>
          <button class="btn btn-cyan d-none d-sm-inline-block" data-bs-toggle="modal" data-bs-target="#modal-index-statistics">
            {{ SVG.pie() }}
            统计数据
          </button>
          <button class="btn btn-cyan d-sm-none btn-icon" data-bs-toggle="modal" data-bs-target="#modal-index-statistics">
            {{ SVG.pie() }}
          </button>
          <button class="btn d-none d-sm-inline-block" data-bs-toggle="modal" data-bs-target="#modal-index-playhistory">
            {{ SVG.history() }}
            播放记录
          </button>
          <button class="btn d-sm-none btn-icon" data-bs-toggle="modal" data-bs-target="#modal-index-playhistory">
            {{ SVG.history() }}
          </button>
        </div>
      </div>
    </div>
  </div>
</div>
{% if ServerSucess %}
{% with curdomainleft = request.host.split(':')[0] %}
<div class="page-body">
  <div class="container-xl">
    <div class="d-grid gap-3 grid-normal-card">
      {% for Library in Librarys %}
        {% if LibrarySyncConf and Library.id|string in LibrarySyncConf %}
        {% set theLibLink = Library.link %}
          {% if "127.0.0.1" in theLibLink[0:16] %}
            {% set theLibLink = theLibLink|replace("127.0.0.1",curdomainleft,1) %}
          {% elif "localhost" in theLibLink[0:16] %}
            {% set theLibLink = theLibLink|replace("localhost",curdomainleft,1) %}
          {% endif %}
          <a class="card card-link-pop rounded-3 overflow-hidden library-{{ Library.id }}" href="{{ theLibLink }}" target="_blank">
          {% if Library.image %}
            <custom-img img-class="w-100"
                        img-src="{{ Library.image }}"
                        img-ratio="50%"
                        img-style="object-fit: cover;"
            ></custom-img>
          {% else %}
            <custom-plex-library-img img-src-list='{{ Library.image_list }}'></custom-plex-library-img>
          {% endif %}
            <div class="m-2 text-center">
              {{ Library.name }}
            </div>
          </a>
        {% endif %}
      {% endfor %}
    </div>
  </div>
</div>
{% if Resumes %}
<div class="container-xl">
  <div class="page-header d-print-none">
    <div class="row align-items-center">
      <div class="col">
        <h2 class="page-title">
          正在观看
        </h2>
      </div>
    </div>
  </div>
</div>
<div class="page-body">
  <div class="container-xl">
    <div class="d-grid gap-3 grid-normal-card align-items-start">
      {% for Resume in Resumes %}
        {% set theLibLink = Resume.link %}
        {% if "127.0.0.1" in theLibLink[0:16] %}
          {% set theLibLink = theLibLink|replace("127.0.0.1",curdomainleft,1) %}
        {% elif "localhost" in theLibLink[0:16] %}
          {% set theLibLink = theLibLink|replace("localhost",curdomainleft,1) %}
        {% endif %}
      <a class="card card-link-pop rounded-3 overflow-hidden resume-{{ Resume.id }}" href="{{ theLibLink }}" target="_blank">
        <custom-img img-class="w-100"
                    img-src="{{ Resume.image }}"
                    img-ratio="50%"
                    img-style="object-fit: cover;"
        ></custom-img>
        <span class="badge badge-pill {% if Resume.type == '电影' %}bg-green{% else %}bg-blue{% endif %}" style="position: absolute; top: 10px; left: 10px">
          {{ Resume.type }}
        </span>
        {% if Resume.percent %}
        <div class="card-progress" style="overflow: hidden">
          <div class="progress-bar bg-green" style="width:{{ Resume.percent }}%" role="progressbar" aria-valuenow="{{ Resume.percent }}" aria-valuemin="0" aria-valuemax="100">
          </div>
        </div>
        {% endif %}
        <div class="m-2 text-center" style="-webkit-line-clamp:1; display: -webkit-box; -webkit-box-orient:vertical; overflow:hidden; text-overflow: ellipsis;">
          {{ Resume.name }}
        </div>
      </a>
      {% endfor %}
    </div>
  </div>
</div>
{% endif %}
{% if Latests %}
<div class="container-xl">
  <div class="page-header d-print-none">
    <div class="row align-items-center">
      <div class="col">
        <h2 class="page-title">
          最新入库
        </h2>
      </div>
    </div>
  </div>
</div>
<div class="page-body">
  <div class="container-xl">
    <div class="d-grid gap-3 grid-media-card align-items-start">
      {% for Latest in Latests %}
      {% set theLibLink = Latest.link %}
        {% if "127.0.0.1" in theLibLink[0:16] %}
          {% set theLibLink = theLibLink|replace("127.0.0.1",curdomainleft,1) %}
        {% elif "localhost" in theLibLink[0:16] %}
          {% set theLibLink = theLibLink|replace("localhost",curdomainleft,1) %}
        {% endif %}
      <a class="card card-link-pop overflow-hidden rounded-3 latest-{{ Latest.id }}" href="{{ theLibLink }}" target="_blank">
        <custom-img img-class="w-100"
                    img-src="{{ Latest.image }}"
                    img-ratio="150%"
                    img-style="object-fit: cover;"
        ></custom-img>
        <span class="badge badge-pill {% if Latest.type == '电影' %}bg-green{% else %}bg-blue{% endif %}" style="position: absolute; top: 10px; left: 10px">
          {{ Latest.type }}
        </span>
        <div class="m-2 text-center" style="-webkit-line-clamp:1; display: -webkit-box; -webkit-box-orient:vertical; overflow:hidden; text-overflow: ellipsis;">{{ Latest.name }}</div>
      </a>
      {% endfor %}
    </div>
  </div>
</div>
{% endif %}
{% endwith %}
{% else %}
{{ OOPS.systemerror('媒体服务器连接失败！', '当前无法连接媒体服务器获取数据，请确认Emby/Jellyfin/Plex配置是否正确。') }}
{% endif %}
<div class="modal modal-blur fade" id="index-mediasync-modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-md modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="card border-0">
        <div class="card-body text-center">
          <div class="mb-3">
            <span class="avatar avatar-xl avatar-rounded"
                  style="background-image: url('../static/img/mediaserver/{{ MediaServerType }}.png')"></span>
          </div>
          <div class="card-title mb-1">{{ MediaServerType|title }}</div>
          <div id="mediasync_status"></div>
        </div>
        <details class="m-3">
            <summary class="summary">
              媒体库列表
            </summary>
            <div class="row mt-2">
              <div class="form-selectgroup">
                {% for Library in Librarys %}
                <label class="form-selectgroup-item">
                  <input type="checkbox" name="sync_library" value="{{ Library.id }}" class="form-selectgroup-input"
                      {% if Library.id in LibrarySyncConf %}checked{% endif %}
                  >
                  <span class="form-selectgroup-label">{{ Library.name }}</span>
                </label>
                {% endfor %}
              </div>
            </div>
          </details>
        <div class="card-progress">
          <div class="progress-bar bg-green" id="mediasync_process_bar" style="width: 0" role="progressbar"
               aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
        </div>
        <div class="d-flex">
          <a href="javascript:save_media_config()" id="save_mediasync_btn" class="card-btn">保存</a>
          <a href="javascript:start_media_sync(true)" id="mediasync_btn" class="card-btn">开始同步</a>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="modal modal-blur fade" id="modal-index-playhistory" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">播放记录</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="card-body card-body-scrollable card-body-scrollable-shadow p-0 overflow-hidden">
          <div class="divide-y">
            {% for Activity in Activitys %}
              <div>
                <div class="row">
                  <div class="col-auto">
                <span class="avatar">
                  {% if Activity.type == "LG" %}
                    {{ SVG.user() }}
                  {% else %}
                    {{ SVG.player_play() }}
                  {% endif %}
                </span>
                  </div>
                  <div class="col">
                    <div class="text-truncate">
                      {{ Activity.event }}
                    </div>
                    <div class="text-muted">{{ Activity.date }}</div>
                  </div>
                  <div class="col-auto align-self-center">
                    <div class="bg-primary"></div>
                  </div>
                </div>
              </div>
            {% endfor %}
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
      </div>
    </div>
  </div>
</div>
<div class="modal modal-blur fade" id="modal-index-statistics" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">统计数据</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body py-0">
        <div class="row">
          <div class="col-lg-4 mt-3">
            <div class="card">
              <div class="card-body">
                <div class="d-flex align-items-center">
                  <div class="subheader">电影</div>
                </div>
                <div class="d-flex align-items-baseline">
                  <div class="h1 mb-0 me-2">{{ MediaCount.MovieCount }}</div>
                </div>
              </div>
              <div class="card-progress" style="overflow: hidden">
                <div class="progress-bar bg-green" style="width:0%" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
              </div>
            </div>
          </div>
          <div class="col-lg-4 mt-3">
            <div class="card">
              <div class="card-body">
                <div class="d-flex align-items-center">
                  <div class="subheader">电视剧/动漫</div>
                </div>
                <div class="d-flex align-items-baseline">
                  <div class="h1 mb-0 me-2">{{ MediaCount.SeriesCount }}</div>
                  <div class="me-auto">
                  <span class="text-green d-inline-flex align-items-center lh-1">
                    {{ MediaCount.EpisodeCount }}
                  </span>
                  </div>
                </div>
              </div>
              <div class="card-progress" style="overflow: hidden">
                <div class="progress-bar bg-green" style="width:0%" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
              </div>
            </div>
          </div>
          <div class="col-lg-4 mt-3">
            <div class="card">
              <div class="card-body">
                <div class="d-flex align-items-center">
                  <div class="subheader">存储空间</div>
                </div>
                <div class="d-flex align-items-baseline">
                  <div class="h1 mb-0 me-2">{{ TotalSpace }}</div>
                </div>
              </div>
              <div class="card-progress" style="overflow: hidden">
                <div class="progress-bar bg-green" style="width:{{ UsedPercent }}%" role="progressbar" aria-valuenow="{{ UsedPercent }}" aria-valuemin="0" aria-valuemax="100"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="row mt-3">
          <div id="index_statistics_chart" style="height: 20rem"></div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
  //显示媒体库同步框
  function show_mediasync_modal() {
    //获取同步状态
    ajax_post("refresh_process", {type: "mediasync"}, function (ret) {
      if (ret.code === 0 && ret.value < 100) {
        //同步中
        $("#index-mediasync-modal").modal('show');
        start_media_sync(false);
      } else {
        //没有在同步，获取目前同步的数据情况
        ajax_post("mediasync_state", {}, function (ret) {
          if (ret.code === 0) {
            $("#mediasync_status").text(ret.text);
          }
          $("#mediasync_btn").text("开始同步")
              .attr("href", "javascript:start_media_sync(true)");
          $("#save_mediasync_btn").show();
          $("#index-mediasync-modal").modal('show');
        }, true, false);
      }
    }, true, false);
  }

  //关闭媒体库同步框
  function close_mediasync_modal() {
    $("#index-mediasync-modal").modal('hide');
  }

  //开始媒体库同步
  function start_media_sync(flag) {
    $("#mediasync_btn").text("关闭")
        .attr("href", "javascript:close_mediasync_modal()");
    $("#save_mediasync_btn").hide();
    if (flag) {
      ajax_post("start_mediasync", {
        "librarys": select_GetSelectedVAL("sync_library")
      }, function (ret) {
        setTimeout("start_mediasync_progress()", 1000);
      }, true, false);
    } else {
      setTimeout("start_mediasync_progress()", 1000);
    }
  }

  // 保存媒体库配置
  function save_media_config(){
    let params = {
      "key": "SyncLibrary",
      "value": select_GetSelectedVAL("sync_library")
    };
    ajax_post("set_system_config", params, function (ret) {
      $("#index-mediasync-modal").modal('hide');
      window_history_refresh();
    });
  }

  // 停止刷新进度
  function stop_mediasync_progress() {
    if (MediaSyncProgressEs) {
      MediaSyncProgressEs.close();
      MediaSyncProgressEs = undefined;
    }
  }

  //刷新进度
  var MediaSyncProgressEs;
  function start_mediasync_progress() {
    stop_mediasync_progress();
    MediaSyncProgressEs = new EventSource(`stream-progress?type=mediasync`);
    MediaSyncProgressEs.onmessage = function (event) {
      let ret = JSON.parse(event.data);
      if (ret.code === 0) {
        $("#mediasync_process_bar").attr("style", "width: " + ret.value + "%")
            .attr("aria-valuenow", ret.value);
        $("#mediasync_status").text(ret.text);
      }
      if ($("#index-mediasync-modal").is(":hidden")) {
        stop_mediasync_progress();
      }
    }
  }

</script>
<script type="text/javascript">

  var chart_statistics = undefined;

  // 加载图表
  $('#modal-index-statistics').off('shown.bs.modal').on('shown.bs.modal', function (e) {
    // 请求数据
    ajax_post("get_transfer_statistics", {}, function(ret){

      // 电影变化图
      if (typeof (chart_statistics) != 'undefined')
        chart_statistics.dispose();

      chart_statistics = echarts.init(document.getElementById("index_statistics_chart"), null, {
        renderer: 'canvas',
        useDirtyRect: false
      });

      const option = {
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['电影', '电视剧', '动漫'],
          textStyle: {
            color: '#206bc4'
          }
        },
        toolbox: {
          feature: {

          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: ret.Labels
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '电影',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: ret.MovieNums
          },
          {
            name: '电视剧',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: ret.TvNums
          },
          {
            name: '动漫',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: ret.AnimeNums
          }
        ]
      };
      chart_statistics.setOption(option);
    });
  });

  $(document).ready(function () {
    // 响应大小调整
    window.onresize = function () {
      if(chart_statistics) {
        chart_statistics.resize();
      }
    };
  });

</script>
